import { createRouter, createWebHashHistory } from 'vue-router'
import { initializeDefaultData } from '@/utils/storage'
import { useCateStore, useBookmarkStore } from '@/store'

import BookView from '@/views/book/index.vue'
import HomeView from '@/views/home/index.vue'
import SettingView from '@/views/setting/index.vue'
import UserView from '@/views/user/index.vue'
import DefaultLayout from '@/layout/default-layout.vue'

const routes = [
  {
    path: '/',
    redirect: '/home',
    name: 'index',
    component: DefaultLayout,
    children: [
      { path: '/home', component: HomeView, name: 'home' },
      { path: '/book', component: BookView, name: 'book' },
      { path: '/user', component: UserView, name: 'user' },
      { path: '/setting', component: SettingView, name: 'setting' },
    ]
  },
  // 将匹配所有路径并重定向到首页
  { path: '/:pathMatch(.*)*', redirect: '/' }
]

// const routes = [
//   { path: '/', component: DefaultLayout },
//   { path: '/home', component: HomeView },
//   { path: '/book', component: BookView },
//   { path: '/user', component: UserView },
//   { path: '/setting', component: SettingView },
//   // 将匹配所有路径并重定向到首页
//   { path: '/:pathMatch(.*)*', redirect: '/' }
// ]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

let isFirstLoad = true;
router.beforeEach((to, from, next) => {
  if (!from.name || isFirstLoad) {
    console.log("初始化数据！");
    isFirstLoad = false;
    try {
      initializeDefaultData()
      useCateStore().onLoadCateList()
      useBookmarkStore().onLoadBookmarkList()
    } catch (error) {
      console.error('Failed to initialize default data:', error);
    }
  }
  next()
})

export default router